package com.itheima.filedownload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/downloadServlet")
public class FileDownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //通过key获得value
        String filename = request.getParameter("filename");
        System.out.println(filename);
        //找到文件,先获取servletcontext对象
        ServletContext sc = getServletContext();


        //解决文件名为中文的乱码问题
        String filenameutf8 = URLEncoder.encode(filename, "utf-8");
        String realPath = sc.getRealPath("/WEB-INF/"+filename);
        //设置文件下载时的类型为附件
        response.setHeader("Content-Disposition","attachment;filename="+filenameutf8);


        //将文件封装成一个文件对象
        File file = new File(realPath);
        //判断文件是否存在
        if (file.exists()) {
            //通过servletcontext对象告诉浏览器文件的类型
            String mimeType = sc.getMimeType(filename);
            //告诉浏览器类型
            response.setContentType(mimeType);
            //读取文件之后,将文件通过网络输出流传给浏览器
            FileInputStream fis = new FileInputStream(file);
            //通过响应对象获得网络输出流对象
            ServletOutputStream netOutput = response.getOutputStream();

            //读取文件,一次读取一个字节数组
            byte[] buf = new byte[1024];
            int len = 0;
            while((len=fis.read(buf))!=-1)
            {
                netOutput.write(buf,0,len);
                netOutput.flush();
            }
            //释放资源
            fis.close();
            netOutput.close();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
